package com.etc.order.frontend.redis.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.etc.order.common.domain.OrderDetail;
import com.etc.order.common.domain.OrderMaster;
import com.etc.order.common.domain.ProductInfo;
import com.etc.order.common.domain.User;
import com.etc.order.common.enums.OrderStatusEnum;
import com.etc.order.common.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class TopicMessageListener implements MessageListener {
    @Resource
    @Reference
    private OrderMasterService orderMasterService;

    @Resource
    @Reference
    private OrderDetailService orderDetailService;

    @Resource
    @Reference
    private ProductInfoService productInfoService;

    @Resource
    @Reference
    private UserService userService;

    @Resource
    @Reference
    private ShoppingCartService shoppingCartService;

    /**
     * 处理超时未付款的订单
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        //String topic = new String(channel);
        String expireKey = new String(body);
        String orderId = expireKey.split(":")[1];
        log.info("Order expired:" + orderId);
        OrderMaster orderMaster = orderMasterService.findByOrderId(orderId);
        if (orderMaster == null) {
            log.info("Not a order expired, no more operations.");
            return;
        }
        if (orderMaster.getOrderStatus().intValue() == OrderStatusEnum.FINISHED.getCode()) {
            log.info("Order has already finished, no more operations.");
            return;
        }
        List<OrderDetail> orderDetails = orderDetailService.findOrderDetailByOrderId(orderId, 0, 999);
        for (OrderDetail orderDetail : orderDetails) {
            ProductInfo productInfo = productInfoService.getOne(orderDetail.getProductId());
            productInfoService.decreaseStock(orderDetail.getProductId(), productInfo.getProductStock() + orderDetail.getProductQuantity());
        }
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        orderMaster.setUpdateTime(new Date(System.currentTimeMillis()));
        orderMasterService.update(orderMaster);
        User user = userService.findByUsername(orderMaster.getBuyerName());
        if (user != null) {
            shoppingCartService.deleteByUid(user.getUid());
        }
    }
}
